package com.zoe.vhr.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zoe.vhr.config.ProjectConfig;
import com.zoe.vhr.mapper.HrMapper;
import com.zoe.vhr.mapper.RoleMapper;
import com.zoe.vhr.model.Hr;
import com.zoe.vhr.model.Role;
import com.zoe.vhr.service.HrService;
import com.zoe.vhr.util.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/26
 * @Description
 */
@Service
public class HrServiceImpl implements HrService {
    private static final Logger logger = LoggerFactory.getLogger(HrServiceImpl.class);
    @Autowired
    ProjectConfig projectConfig;
    @Autowired
    HrMapper hrMapper;

    @Autowired
    RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StrUtil.isBlank(username)) {
            throw new RuntimeException("用户名不可为空");
        }
        Hr hr = hrMapper.loadUserByUsername(username);
        if (ObjectUtil.isNull(hr)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        Set<Role> roleList = roleMapper.listRoleByHrId(hr.getId());
        hr.setRoles(roleList);
        return hr;
    }

    @Override
    public List<Hr> listAllHrs(Hr hr) {
        Hr sessionHr = SecurityUtil.getCurrentUser();
        List<Hr> hrs = hrMapper.listAllHrs(hr, sessionHr.getId());
        List<Hr> sortList = hrs.stream().sorted(Comparator.comparing(Hr::getId)).collect(Collectors.toList());
        return sortList;
    }

    @Override
    public int updateHr(Hr hr) {
        return hrMapper.updateHr(hr);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateHrWithRole(Integer hrId, Integer[] roleIds) {
        int count = hrMapper.deleteRoleWithHRId(hrId);
        int saveCount = 0;
        if (ArrayUtil.isNotEmpty(roleIds)) {
            saveCount = hrMapper.insertRoleWithHRId(hrId, roleIds);
        }
        return saveCount;
    }

    @Override
    public int saveHr(Hr hr, MultipartFile multipartFile) {
        System.out.println(hr);
        savaAvatar(multipartFile);
        return 0;
    }

    public String savaAvatar(MultipartFile multipartFile) {
        logger.info("开始上传头像===>{}", DateUtil.now());
        String originalFilename = multipartFile.getOriginalFilename();
        int idx = StrUtil.lastIndexOf(originalFilename, ".", originalFilename.length(), false);
        String suffix = StrUtil.sub(originalFilename, idx, originalFilename.length() + 1);
        String fileName = UUID.fastUUID().toString();
        String path = projectConfig.getUploadPath() + "avatar" + File.separator + DateUtil.today() + File.separator + fileName + suffix;
        logger.info("文件上传路径===>{}", path);
        try (
            // 获取流
            InputStream inputStream = multipartFile.getInputStream();
            // 文件夹不存在则自动创建文件夹;
            OutputStream outputStream = FileUtil.getOutputStream(path)
        ) {
            // 流操作
            IoUtil.copy(inputStream, outputStream);
        } catch (IOException e) {
            logger.info("开始上传异常===>{}", DateUtil.now());
            e.printStackTrace();
        }
        logger.info("开始上传结束===>{}", DateUtil.now());
        return path;
    }
}
